<?php

class SmartyView {

        static protected $link = NULL;

        public function __construct() {
                //如果不为空，则跳过此步
                if (!is_null(self::$link)) {
                        return;
                }
                //实例化smarty对象
                $smarty = new Smarty();
                //模板目录
                $smarty->template_dir = APP_TPL_PATH . '/' . CONTROL;
                //编译目录
                $smarty->compile_dir = APP_COMPILE_PATH;
                //缓存目录
                $smarty->cache_dir = APP_CACHE_PATH;
                //开始定界符
                $smarty->left_delimiter = C('LEFT_DELIMITER');
                //结束定界符
                $smarty->right_delimiter = C('RIGHT_DELIMITER');
                //是否缓存
                $smarty->caching = C('SMARTY_CACHE_ON');
                //缓存时间
                $smarty->cache_lifetime = C('SMARTY_CACHE_LIFE');
                //保存到属性中
                self::$link = $smarty;
        }

        protected function display($var = NULL) {
                //display方法
                $fullPath = $this->get_tpl($var);
                //如果文件不存在，則報錯
                if (!is_file($fullPath))
                        halt('模板', $fullPath);
                //调用smarty的display方法
                self::$link->display($fullPath, $_SERVER['REQUEST_URI']);
        }

        protected function assign($var, $value) {
                //调用smarty的assign方法，传入参数
                self::$link->assign($var, $value);
        }

        //判断是否缓存
        protected function is_cached($tpl = NULL) {
                $tpl = $this->get_tpl($tpl);
                return self::$link->is_cached($tpl, $_SERVER['REQUEST_URI']);
        }

        //清除缓存
        protected function clear_cache() {
                self::$link->clear_cache();
        }

        protected function get_tpl($var = NULL) {
                if (empty($var)) {
                        //如果不传入任何参数，操作方法
                        $fullPath = APP_TPL_PATH . '/' . CONTROL . '/' . METHOD . '.html';
                } else {
                        //如果传入参数
                        $type = ltrim(strrchr($var, '.'), '.');
                        if (!empty($type)) {
                                $path = $var;
                                //有后缀
                        } else {
                                //没有后缀加上後綴
                                $path = $var . '.html';
                        }
                        //全路徑
                        $fullPath = APP_TPL_PATH . '/' . CONTROL . '/' . $path;
                }
                return $fullPath;
        }

}
